package org.yufan.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yufan.bean.Cart;
import org.yufan.bean.User;
import org.yufan.cart.service.CartService;
import org.yufan.exception.CustomException;
import org.yufan.interceptor.UserThreadLocal;
import org.yufan.result.Result;
import org.yufan.result.ResultUtils;
import org.yufan.service.CartCookieService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created by zxd on 2018/4/12.
 */
@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private CartCookieService cartCookieService;

    private Logger LOGGER= LoggerFactory.getLogger(CartController.class);

    @RequestMapping("/add/{itemId}")
    public String addItemToCart(@PathVariable("itemId") Long itemId, HttpServletRequest request, HttpServletResponse response) throws IOException, CustomException {
        //获得用户信息
        User user= UserThreadLocal.get();
        //判断用户是否登录
        if(user==null){
            //存到cookie TODO
            cartCookieService.addItemToCart(itemId, request, response);
        }else {
            LOGGER.info("存储到数据库!商品id{},用户id{}",itemId,user.getId());
            //存到数据库

            cartService.addItemToCart(itemId,user.getId());
        }
        return "redirect:/cart/show.html";
    }

    @RequestMapping(value = "/update/{num}")
    @ResponseBody
    public Result  updateNum(Long cartId,@PathVariable("num")Integer num,HttpServletRequest request, HttpServletResponse response,Long itemId){
        User user=UserThreadLocal.get();
        if(user==null){
            //没有登录 TODO
            LOGGER.info("没有登录修改购物车的数量，存在cookie，itemId是{}",itemId);
            cartCookieService.updateNum(itemId,num,request,response);
        }else{
            //登录
            cartService.updateCartNum(cartId,num);
        }
        return ResultUtils.buildSuccess();
    }

    @RequestMapping(value = "/show",method = RequestMethod.GET)
    public String showCart(Model model,HttpServletRequest request){
        User user=UserThreadLocal.get();
        List<Cart> cartList=null;
        if(user==null){
            //没有登录 TODO
            cartList=cartCookieService.queryCartList(request);
        }else{
            //登录
            cartList=cartService.queryCartList(user.getId());
            model.addAttribute("user",user);
        }
        model.addAttribute("cartList",cartList);
        return "cart";
    }



}
